import React, { useState, useEffect, createContext } from 'react';
import { Row, Col, Form, Input, Icon, Button, message, Select, TreeSelect } from 'antd';
import request from '@/utils/request';
const { TreeNode } = TreeSelect;
import PropTypes from 'prop-types';
import { connect } from 'dva';

function AreaSelect(props) {
  const [TreeData, setTreeData] = useState([]);
  const [selectValue, setSelectValue] = useState(props.value);
  // 初始化
  useEffect(() => {
    /**
     * 这里再useEffect中设置了一个是否不在渲染的flag（ignore）。
     * 如果ignore为false，这更新state，如果为true则不再更新state。
     * 当组件卸载的时候，将ignore设置为true，即当异步请求回来的时候组件已经卸载了，但是判定为true就不会更新state。
     */
    let ignore = false;
    // 初始化请求
    queryChildren(-1).then(res => {
      if (res.length > 0) {
        let node = {};
        let arr = [];
        res.map((item, index) => {
          node = item;
          if (item.childrenCount !== 0) {
            node.children = [];
            node.isLeaf = false;
          } else {
            node.isLeaf = true;
          }
          arr.push(node);
        });
        if (!ignore) setTreeData(arr);
      }
    });

    (function dataTimeInterval() {
      setTimeout(() => {
        dataTimeInterval();
      }, 1000);
    })();
    return _ => {
      ignore = true;
    };
  }, []);
  // 监听value的变化
  useEffect(() => {
    setSelectValue(props.value);
  }, [props.value]);

  const init = () => {
    queryChildren(-1).then(res => {
      if (res.length > 0) {
        let node = {};
        let arr = [];
        res.map((item, index) => {
          node = item;
          if (item.childrenCount !== 0) {
            node.children = [];
            node.isLeaf = false;
          } else {
            node.isLeaf = true;
          }
          arr.push(node);
        });
        setTreeData(arr);
      }
    });
  };

  // 异步加载区域选择
  const onLoadData = treeNode =>
    new Promise(resolve => {
      const commonRegionId = treeNode.props.dataRef.commonRegionId;
      queryChildren(commonRegionId).then(res => {
        if (res.length > 0) {
          let node = {};
          let arr = [];
          res.map((item, index) => {
            node = item;
            if (item.childrenCount !== 0) {
              node.isLeaf = false;
            } else {
              node.isLeaf = true;
            }
            arr.push(node);
          });
          setTreeData([...TreeData, ...arr]);
        }
        resolve();
      });
    });

  async function queryChildren(commonRegionId) {

    return request('orgauth/CommonRegionController/qryRegionsByParentId.do', {
      data: {
        parentId: commonRegionId,
      },
    });
  }

  // 由接口决定，根据parentOrgId 获取同级元素
  const getParentId = parRegionId => {
    return TreeData.filter(item => {
      return item.parRegionId === parRegionId;
    });
  };

  // 遍历树
  const renderTreeNode = parRegionId => {
    const tmp = getParentId(parRegionId);
    if (tmp.length > 0) {
      return tmp.map(item => {
        return (
          <TreeNode
            title={item.regionName}
            value={item.commonRegionId}
            key={item.commonRegionId}
            isLeaf={item.isLeaf}
            dataRef={item}
          >
            {renderTreeNode(item.commonRegionId)}
          </TreeNode>
        );
      });
    }
  };

  const areaChange = (value, label, extra) => {
    extra.triggerNode
      ? (props.onChange(extra.triggerNode.props.dataRef),
        setSelectValue(extra.triggerNode.props.dataRef))
      : (props.onChange(undefined),
        setSelectValue({
          regionName: null,
          commonRegionId: null,
        }));
  };

  const getValue = value => {
    return value.regionName;
  };

  return (
    <TreeSelect
      allowClear={props.allowClear}
      dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
      loadData={onLoadData}
      placeholder={props.placeholder}
      onChange={areaChange}
      value={getValue(selectValue)}
      disabled={props.disabled}
    >
      {renderTreeNode(-1)}
    </TreeSelect>
  );
}

AreaSelect.defaultProps = {
  value: {
    orgName: null,
    orgId: null,
  },
  placeholder: '',
  disabled: false,
  onChange: () => {},
  allowClear: false,
};

AreaSelect.propTypes = {
  value: PropTypes.shape({
    regionName: PropTypes.string,
    commonRegionId: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  }),
  placeholder: PropTypes.string,
  onChange: PropTypes.func,
  disabled: PropTypes.bool,
  allowClear: PropTypes.bool,
};

export default connect(({}) => ({
  forwardRef: true,
}))(AreaSelect);
